package org.biogroovy.io.journaltocs;

import groovy.util.slurpersupport.GPathResult
import groovy.util.slurpersupport.NodeChild

import org.biogroovy.conf.BioGroovyConfig
import org.biogroovy.io.AbsXmlSlurper
import org.biogroovy.io.IFetcher
import org.biogroovy.models.Journal
import org.biogroovy.models.JournalRights

/**
 * This class reads Journal information from the JournalTOCS web service.
 */
public class JournalTOCSJournalReader extends AbsXmlSlurper<Journal>{

	private static final String DATABASE_NAME = "journaltocsjournal"
	private Map nsMap = [
		"dc":"http://purl.org/dc/elements/1.1/",
		"mn":"http://usefulinc.com/rss/manifest/",
		"content":"http://purl.org/rss/1.0/modules/content/",
		"prism":"http://prismstandard.org/namespaces/1.2/basic/",
		"rdf":"http://www.w3.org/1999/02/22-rdf-syntax-ns#"
	]

	private Map<String, String> paramMap = new HashMap<>();

	/**
	 * Constructor.
	 */
	public JournalTOCSJournalReader() {
		ConfigObject conf = BioGroovyConfig.getConfig();
		this.paramMap['journaltocs.userid'] = conf.journaltocs.userid
	}

	@Override
	public void parse(Journal journal, NodeChild node) {
		if(node != null) {
			journal.title = node.'prism:publicationName';
			journal.siteUrl = node.link;
			journal.imageUrl = node.image.link;
			journal.issn = node.'prism:issn';
			journal.issue = node.'prism:number';
			journal.volume = node.'prism:volume';
			journal.rssUrl = "http://www.journaltocs.ac.uk/api/journals/${journal.issn}?output=articles&user=mark.fortner@aspenbiosciences.com"
			journal.rights = JournalRights.lookup(node.'dc:rights'.text())
		}
	}

	@Override
	public Journal read(InputStream inputStream) throws IOException {

		XmlSlurper slurper = new XmlSlurper(false, true);
		
		GPathResult root = slurper.parse(inputStream)
		root.declareNamespace(nsMap)

		Journal journal = new Journal()
		parse(journal, root?.'item'.getAt(0));
		return journal

	}



	@Override
	public List<Journal> readList(InputStream inputStream) throws IOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Journal fetch(String id) throws IOException {
		URL url = getUrl(id, this.paramMap);
		return read(url.openStream());
	}

	@Override
	public URL getUrl(String id, Map<String, String> paramMap) {
		return new URL("http://www.journaltocs.ac.uk/api/journals/${id}?output=journals&user=${paramMap['journaltocs.userid']}")
	}

	@Override
	public String getDatabaseName() {
		return "journaltocs"
	}

	@Override
	public List<Journal> fetchAll(String id) throws IOException {
		// NO-OP
		return null;
	}

	@Override
	protected void parseDbReferences(NodeChild root, Journal node) {
		// NO-OP

	}

	@Override
	public IFetcher<Journal> getNewInstance() {
		return new JournalTOCSJournalReader();
	}
}
